package org.darkforest.common.services.impl;

import org.darkforest.common.services.DeliverService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.AreaMapper;
import org.darkforest.dao.mapper.StoreMapper;
import org.darkforest.dao.mapper.TransportExtendMapper;
import org.darkforest.dao.mapper.TransportMapper;
import org.darkforest.common.services.TransportService;
import org.darkforest.model.*;
import org.darkforest.vo.TransportFeeQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liu on 15/1/18.
 */
@Service("transportService")
public class TransportServiceImpl implements TransportService {
    @Autowired
    private TransportMapper transportMapper;
    @Autowired
    private TransportExtendMapper transportExtendMapper;
    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private DeliverService deliverService;

    public void selectPageTransport(TransportPageBean page) {
        List list = transportMapper.selectListByCondition(page);
        page.setResultList(list);
    }

    public List createArea() {
        List list = new ArrayList();
        Area a1 = new Area();
        a1.setAreaId(1);
        a1.setAreaName("华北");
        a1.setChildrenList(new ArrayList());
        list.add(a1);

        Area a2 = new Area();
        a2.setAreaId(2);
        a2.setAreaName("东北");
        a2.setChildrenList(new ArrayList());
        list.add(a2);

        Area a3 = new Area();
        a3.setAreaId(3);
        a3.setAreaName("华东");
        a3.setChildrenList(new ArrayList());
        list.add(a3);

        Area a4 = new Area();
        a4.setAreaId(4);
        a4.setAreaName("华南");
        a4.setChildrenList(new ArrayList());
        list.add(a4);

        Area a5 = new Area();
        a5.setAreaId(5);
        a5.setAreaName("华中");
        a5.setChildrenList(new ArrayList());
        list.add(a5);

        Area a6 = new Area();
        a6.setAreaId(6);
        a6.setAreaName("西南");
        a6.setChildrenList(new ArrayList());
        list.add(a6);

        Area a7 = new Area();
        a7.setAreaId(7);
        a7.setAreaName("西北");
        a7.setChildrenList(new ArrayList());
        list.add(a7);

        Area a8 = new Area();
        a8.setAreaId(8);
        a8.setAreaName("港澳台");
        a8.setChildrenList(new ArrayList());
        list.add(a8);

        Area a9 = new Area();
        a9.setAreaId(9);
        a9.setAreaName("海外");
        a9.setChildrenList(new ArrayList());
        list.add(a9);
        return list;
    }

    public List<Area> getAreaList(int parentAreaId) {
        return areaMapper.getAreaListByParentId(parentAreaId);
    }

    public int deleteTransportAndExtend(int id) {
        transportMapper.deleteByPrimaryKey(id);
        return transportExtendMapper.deleteByTransPortId(id);
    }


    public int insertTransport(Transport t) {
        return transportMapper.insertSelective(t);
    }

    public int insertTransportExtend(TransportExtendWithBLOBs t) {
        return transportExtendMapper.insertSelective(t);
    }

    public Transport getTransportById(int id) {
        return transportMapper.selectByPrimaryKey(id);
    }

    public TransportVo getTransportVoById(int id) {
        return transportMapper.selectTransportVoByPrimaryKey(id);
    }

    public int copyTransport(int id) {
        TransportVo tVo = transportMapper.selectTransportVoByPrimaryKey(id);
        Transport newTp = new Transport();
        newTp.setStoreId(1);
        newTp.setTitle("(复制)" + tVo.getTitle());
        newTp.setUpdateTime(DateUtil.unixTimeStampInt().intValue());
        insertTransport(newTp);
        TransportExtendWithBLOBs et;
        for (TransportExtend extend : tVo.getTransports()) {
            et = new TransportExtendWithBLOBs();
            et.setTransportTitle("(复制)" + extend.getTransportTitle());
            et.setTransportId(newTp.getId());
            et.setSnum(extend.getSnum());
            et.setSprice(extend.getSprice());
            et.setXnum(extend.getXnum());
            et.setXprice(extend.getXprice());
            et.setIsDefault(extend.getIsDefault());
            et.setAreaName(extend.getAreaName());
            et.setAreaId(extend.getAreaId());
            insertTransportExtend(et);
        }
        return 1;
    }

    /**
     * 查询店铺运费模板
     *
     * @param storeId
     * @param address
     * @return
     */
    @Override
    public BigDecimal selectStoreShipModel(Integer storeId, Address address, BigDecimal amount, BigDecimal freePrice, Integer goodsNum) {
        BigDecimal orderShip = new BigDecimal(0);
        if (address != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("storeId", storeId);
            map.put("areaId", "%," + address.getAreaId() + ",%");
            map.put("areaId1", "%" + address.getAreaId() + ",%");
            map.put("areaId2", "%," + address.getAreaId() + "%");
            List<TransportVo> transportVos = transportMapper.selectStoreShipModel(map);
            //如果购物车总价格小于店铺设定的免运费价格
//        cartInfo.getSubtotal().compareTo(store.getStoreFreePrice())==-1

            if (amount.compareTo(freePrice) == -1) {
                //采用统一运费
                if (transportVos.get(0).getTransports().size() == 1) {
                    orderShip = orderShip.add(transportVos.get(0).getTransports().get(0).getSprice());
                    if (goodsNum > 1) {
                        orderShip = orderShip.add(transportVos.get(0).getTransports().get(0).getXprice().multiply(new BigDecimal((goodsNum - 1))));
                    }
                } else {
                    orderShip = orderShip.add(transportVos.get(0).getTransports().get(1).getSprice());
                    if (goodsNum > 1) {
                        orderShip = orderShip.add(transportVos.get(0).getTransports().get(1).getXprice().multiply(new BigDecimal((goodsNum - 1))));
                    }
                }
            }
        } else {
            if (amount.compareTo(freePrice) == -1) {
                //总价小于免费总费
                orderShip = new BigDecimal(10);
            }
        }
        return orderShip;
    }

    /**
     * 根据商品信息计算运费
     *
     * @param address
     * @param tsParam TODO 按店铺划分商品并计算免运费额度
     * @param storeId
     * @return
     */
    @Override
    public BigDecimal getTransportFee(Address address, List<TransportFeeQuery> tsParam, Integer storeId) {
        BigDecimal fee = new BigDecimal(0);
        BigDecimal goodsAmount = new BigDecimal(0);
        TransportExtend goodsTe = null;
        Store store = storeMapper.selectStoreByPrimaryKey(storeId);
        //商品运费模板
        //查询该店铺的运费模板
        for (TransportFeeQuery param : tsParam) {               //循环商品列表
            //有运单模板时查询模板，没有时使用运费计算
            if (param.getTransportId() == null || param.getTransportId() == 0) {
                  fee = fee.add(param.getGoodsFreight().multiply(new BigDecimal(param.getGoodsNum())));                           //没有设置运费模板的商品，按数量累积运费
//                fee = fee.add(param.getGoodsFreight());                           //主线版本没有设置运费模板的商品，默认运费为发布商品设置的运费 与购买商品数量无关
            } else {
                List<TransportExtend> transportExtends = transportExtendMapper.getTransportExtendsListByTransportId(param.getTransportId());

                for (TransportExtend te : transportExtends) {
                    String areaId = te.getAreaId();                 //获取模板区域id，为空时代表全国，否则以,隔开每个区域id，循环判断
                    if (areaId == null) {
                        goodsTe = te;
                    } else {
                        String[] areas = areaId.split(",");
                        for (String area : areas) {
                            if (area.equals(address.getCityId().toString())) {
                                goodsTe = te;
                                break;
                            }
                        }
                    }
                }

                //根据地址选中的运费模板进行计算
                BigDecimal goodsFee = new BigDecimal(0);
                if (param.getGoodsNum() <= goodsTe.getSnum()) {                         //首重范围内 运费即首运费
                    goodsFee = goodsTe.getSprice();
                } else {
                    //判断续件数量为0 那么运费就是为
                    if (goodsTe.getXnum() != 0) {
                        int czNum = param.getGoodsNum() - goodsTe.getSnum();            //超重数量
                        BigDecimal xz = czNum % goodsTe.getXnum() == 0 ? goodsTe.getXprice().multiply(new BigDecimal(czNum / goodsTe.getXnum())) : goodsTe.getXprice().multiply(new BigDecimal(czNum / goodsTe.getXnum() + 1));            //续重金额
                        goodsFee = goodsTe.getSprice().add(xz);
                    } else {
                        goodsFee = new BigDecimal(0);
                    }

                }
                fee = fee.add(goodsFee);                                            //循环中累积运费
            }
            goodsAmount = goodsAmount.add(param.getGoodsPrice().multiply(new BigDecimal(param.getGoodsNum())));
        }
        //最后与店铺免运费额度做对比，如有额度设置进行对比
        if (store.getStoreFreePrice() != null && store.getStoreFreePrice().compareTo(BigDecimal.ZERO) > 0) {
            fee = store.getStoreFreePrice().compareTo(goodsAmount) < 0 ? new BigDecimal(0) : fee;                         //店铺免运费额度<商品总价时 运费设为0 否则返回运费
        }
        return fee;
    }

}
